#include "irc.h"

void OneConnect(INFO *info) {

   info->s = (struct sockaddr_in *) malloc(sizeof(struct sockaddr_in));

   info->host = gethostbyname(info->server);

   info->fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
   info->s->sin_family = AF_INET;
   info->s->sin_port = htons(info->port);
   memcpy(&info->s->sin_addr.s_addr, info->host->h_addr, info->host->h_length);

   info->con = connect(info->fd, (const struct sockaddr *) info->s, sizeof(struct sockaddr_in));
   if(info->con != 0) {
      printf("Impossivel conectar!\n");
      exit(0);
   }

   info->f = fdopen(info->fd,"r");

   ssock(info->fd, "NICK %s\r\n", info->nick);
   ssock(info->fd, "USER %s 8 * :%s\r\n", info->ident, info->name);
   ssock(info->fd, "MODE %s +p\r\n", info->nick);
   ssock(info->fd, "NICKSERV IDENTIFY %s\r\n", info->password);
   ssock(info->fd, "JOIN #sget\r\n");

}

void ssock(int fd, const char *format, ...) {

   va_list l;
   char buffer[512];
   int num;

   va_start(l, format);
   num = vsnprintf(buffer, 512, format, l);
   va_end(l);

   write(fd, buffer, num);

}

char * rsock(FILE *fp) {

   char *reciev, buffer[1024];
   fgets(buffer, 1024, fp);
   chrdel('\r',buffer);
   chrdel('\n',buffer);

   reciev = strdup(buffer);

   return reciev;

}
